import { defineStore } from 'pinia'

export interface AmapKeys {
  amapKey: string
  amapSafeCode: string
  amapWebServiceKey: string
}

export const useAmapKeyStore = defineStore('useAmapKeyStore', {
  state: (): AmapKeys => {
    return {
      amapKey: '', // 高德 JSAPI key
      amapSafeCode: '', // 高德 JSAPI 安全密钥
      amapWebServiceKey: '', // 高德 Web服务 key
    }
  },
  actions: {
    // 设置全部 key
    SET_ALL_KEY({ amapKey, amapSafeCode, amapWebServiceKey }: AmapKeys) {
      this.SET_AMAP_KEY(amapKey)
      this.SET_AMAP_SAFE_CODE(amapSafeCode)
      this.SET_AMAP_WEB_SERVICE_KEY(amapWebServiceKey)
    },
    // 设置高德 JSAPI key
    SET_AMAP_KEY(key: string) {
      if (key) {
        this.amapKey = key || import.meta.env.VITE_GD_MAP_KEY
      }
    },
    // 设置高德 JSAPI 安全密钥
    SET_AMAP_SAFE_CODE(key: string) {
      if (key) {
        this.amapSafeCode = key || import.meta.env.VITE_GD_MAP_SAFECODE
        // @ts-ignore-next-line
        // #ifdef H5
        window._AMapSecurityConfig = {
          securityJsCode: key || import.meta.env.VITE_GD_MAP_SAFECODE,
        }
        // #endif
      }
    },
    // 设置高德 Web服务 key
    SET_AMAP_WEB_SERVICE_KEY(key: string) {
      if (key) {
        this.amapWebServiceKey = key || import.meta.env.VITE_GD_WEB_MAP_KEY
      }
    },
  },
  getters: {
    getAmapKey(state) {
      return state.amapKey
    },
    getAmapSafeCode(state) {
      return state.amapSafeCode
    },
    getAmapWebServiceKey(state) {
      return state.amapWebServiceKey
    },
  },
})
